package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.RetrofitHelper;
import com.rockcent.mall.helper.UserHelper;
import com.rockcent.mall.lib.domain.Mall;
import com.rockcent.mall.lib.domain.MallWechatMenuConfig;
import com.rockcent.mall.lib.dto.MallWechatMenuConfigDto;
import com.rockcent.mall.lib.dto.MallWechatMenuListDTO;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.MallWechatMenuConfigHelper;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MallWechatMenuConfigRepository;
import com.rockcent.service.MallWechatApiService;
import com.rockcent.service.MallWechatMenuConfigSrv;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import retrofit2.Retrofit;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by DK on 16/11/16.
 */
@RestController
public class MallWechatMenuConfigController extends BaseController {
    private final Logger log = LoggerFactory.getLogger(MallWechatMenuConfigController.class);

    @Autowired
    private UserHelper userHelper;

    @Autowired
    private MallWechatMenuConfigRepository mallWechatMenuConfigRepository;

    @Autowired
    private MallRepository mallRepository;

    private MallWechatApiService mallWechatApiService;

    @Autowired
    private MallWechatMenuConfigHelper mallWechatMenuConfigHelper;


    @Autowired
    private MallWechatMenuConfigSrv mallWechatMenuConfigSrvImpl;

    /**
     * @api {get} /mall/wechat/menu/config/save M端微信菜单 菜单新增
     * @apiGroup MALL_WECHAT_MENU
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} name <code>必传参数</code> 菜单名称
     * @apiParam {String} pageUrl <code>必传参数</code> 菜单地址
     * @apiParam {String} menuType <code>必传参数</code> 菜单类型
     * @apiParam {String} materialType 素材类型
     * @apiParam {String} mediaId 素材ID
     * @apiParam {String} materialName 素材名称
     * @apiParam {String} materialUrl 素材链接
     *
     * @apiSuccess {String} success 标识 Y为成功
     *
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *   "success": "Y"
     *   }
     * }
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MENU_CONFIG_SAVE, method = RequestMethod.POST)
    private JsonResult wechatMenuConfigSave(HttpServletRequest request, @RequestBody MallWechatMenuConfigDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if(!mallWechatMenuConfigHelper.checkMallWechatMenuList(dto.getMenuList(),jsonResult)) {
                return;
            }
            List<MallWechatMenuConfig> menuList = mallWechatMenuConfigRepository.findByMallId(userInfoDto.mall.getId());
            mallWechatMenuConfigRepository.delete(menuList);
            mallWechatMenuConfigHelper.saveList(dto.getMenuList(),userInfoDto.mall.getId(),new Long(0));
            releaseWechatMenuConfig(userInfoDto.mall.getId(),dto);
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
            //jsonResult.data = dto.getMenuList();
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/wechat/menu/config/info M端微信菜单 菜单详情
     * @apiGroup MALL_WECHAT_MENU
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {Long} id 菜单ID
     * @apiSuccess {String} name 菜单名称
     * @apiSuccess {String} pageUrl 页面地址 (父菜单为空, 子菜单有值)
     * @apiSuccess {String} menuType 菜单类型
     * @apiSuccess {String} materialType 素材类型
     * @apiSuccess {String} mediaId 素材ID
     * @apiSuccess {String} materialName 素材名称
     * @apiSuccess {String} materialUrl 素材链接
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": [
     *     {
     *       "id": 112,
     *       "dateCreated": "2016-11-21 12:52:26",
     *       "lastUpdated": "2016-11-21 12:52:26",
     *       "name": "baidu",
     *       "menuType": "view",
     *       "pageUrl": "www.baidu.com",
     *       "parentId": 0,
     *       "children": [
     *         {
     *           "id": 113,
     *           "dateCreated": "2016-11-21 12:52:27",
     *           "lastUpdated": "2016-11-21 12:52:27",
     *           "name": "baidu2",
     *           "menuType": "view",
     *           "pageUrl": "www.baidu.com",
     *           "parentId": 112,
     *           "children": [
     *             {
     *               "id": 114,
     *               "dateCreated": "2016-11-21 12:52:27",
     *               "lastUpdated": "2016-11-21 12:52:27",
     *               "name": "baidu3",
     *               "menuType": "view",
     *               "pageUrl": "www.baidu.com",
     *               "parentId": 113,
     *               "children": []
     *             }
     *           ]
     *         }
     *       ]
     *     },
     *     {
     *       "id": 115,
     *       "dateCreated": "2016-11-21 12:52:27",
     *       "lastUpdated": "2016-11-21 12:52:27",
     *       "name": "qq",
     *       "menuType": "view",
     *       "pageUrl": "www.qq.com",
     *       "parentId": 0,
     *       "children": [
     *         {
     *           "id": 116,
     *           "dateCreated": "2016-11-21 12:52:27",
     *           "lastUpdated": "2016-11-21 12:52:27",
     *           "name": "qq2",
     *           "menuType": "view",
     *           "pageUrl": "www.qq.com",
     *           "parentId": 115,
     *           "children": []
     *         }
     *       ]
     *     }
     *   ]
     * }
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MENU_CONFIG_INFO, method = RequestMethod.GET)
    private JsonResult wechatMenuConfigInfo(HttpServletRequest request, MallWechatMenuConfigDto dto){

        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            Long mallId = userInfoDto.mall.getId();
            //如果本地存在菜单直接显示出来，否则调用微信接口获取菜单信息
            List<MallWechatMenuListDTO>  dtoList = getMallWechatMenuListDTOS(mallId);
            log.info("======================>>>toList>>1:"+dtoList);
            if (dtoList == null || dtoList.isEmpty()) {
                //调用微信接口获取菜单信息
                mallWechatMenuConfigSrvImpl.initWechatMenu(mallId);
                dtoList = getMallWechatMenuListDTOS(mallId);
                log.info("======================>>>toList>>2:"+dtoList);
            }
            jsonResult.data = dtoList;
        };
        return doing.go(request, log);
    }

    private List<MallWechatMenuListDTO> getMallWechatMenuListDTOS(Long mallId) {
        List<MallWechatMenuConfig> menuList = mallWechatMenuConfigRepository.findByMallId(mallId);
        return mallWechatMenuConfigHelper.getChildTreeObjects(mallWechatMenuConfigHelper.convertPO2DTO(menuList),0L);
    }

    /**
     * M端微信菜单 发布
     * @param dto
     */
    public void releaseWechatMenuConfig(Long mallId, MallWechatMenuConfigDto dto) throws Exception {
        Mall mall = mallRepository.findOne(mallId);
        String domain = mall.getCustomerClientDomain();
        if (StringUtils.isBlank(domain)) {
            domain = mall.getMobileHostName();
        }
        String url = "http://127.0.0.1:8881";
        Retrofit retrofit = RetrofitHelper.SINGLETON.getRetrofit(url);
        mallWechatApiService = retrofit.create(MallWechatApiService.class);
        mallWechatApiService.releaseWechatMenuConfig(domain, dto).execute();
    }

    /**
     * @api {get} /mall/wechat/material/file_batch_get B端微信素材列表--根据类别分页获取非图文素材列表
     * @apiGroup MALL_WECHAT_MATERIAL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} type <code>必传参数</code> 素材的类型 图片（image）、视频（video）、语音 （voice）
     * @apiParam {String} offset <code>必传参数</code> 从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * @apiParam {String} count <code>必传参数</code> 返回素材的数量
     *
     * @apiSuccess {String} totalCount 该类型的素材的总数
     * @apiSuccess {String} itemCount 本次调用获取的素材的数量
     * @apiSuccess {String} mediaId 图片素材id
     * @apiSuccess {String} updateTime 这篇图文消息素材的最后更新时间
     * @apiSuccess {String} name 文件名称
     * @apiSuccess {String} url 图文页的URL
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *     "code": "1",
     *     "desc": "成功",
     *     "data": {
     *         "totalCount": 13,
     *         "itemCount": 1,
     *         "items": [
     *             {
     *                 "mediaId": "unp1RkB5qsyGcG4QEouF_OfnZMo9oLlOOm1NKblPoaI",
     *                 "updateTime": "2016-09-01 18:41:03",
     *                 "name": "/var/www/html/assets/upload/image/wechat/1472726460316186.jpg",
     *                 "url": "http://mmbiz.qpic.cn/mmbiz_jpg/HtVebh70FQaujkpzQ9pBPic74WfNh26veTOseARVjpDOBvURvafuKib9WLQV77FBboTnNSu2Uwk7mmc9SBkMCdRw/0?wx_fmt=jpeg"
     *             }
     *         ]
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MATERIAL_FILEBATCHGET, method = RequestMethod.GET)
    @ResponseBody
    private JsonResult fileBatchGet(HttpServletRequest request,String type, int offset, int count) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            String domain = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(domain)) {
                domain = mall.getMobileHostName();
            }
            jsonResult.data=mallWechatMenuConfigSrvImpl.materialFileBatchGet(domain,type,offset,count).data;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/wechat/material/news_batch_get B端微信素材列表--根据类别分页获取图文素材列表
     * @apiGroup MALL_WECHAT_MATERIAL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {int} offset <code>必传参数</code> 偏移位置
     * @apiParam {int} count <code>必传参数</code> 返回数量
     *
     * @apiSuccess {String} totalCount 该类型的素材的总数
     * @apiSuccess {String} itemCount 本次调用获取的素材的数量
     * @apiSuccess {String} mediaId 素材id
     * @apiSuccess {String} updateTime 最后更新时间
     * @apiSuccess {String} content 具体内容
     * @apiSuccess {String} thumbMediaId 封面图片素材id
     * @apiSuccess {String} showCoverPic 是否显示封面，0为false，即不显示，1为true，即显示
     * @apiSuccess {String} author 作者
     * @apiSuccess {String} digest 图文消息的摘要
     * @apiSuccess {String} url 图文页的URL
     * @apiSuccess {String} contentSourceUrl 图文消息的原文地址，即点击“阅读原文”后的URL
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": "1",
     *     "desc": "成功",
     *     "data": {
     *         "totalCount": 12,
     *         "itemCount": 1,
     *         "items": [
     *             {
     *                 "mediaId": "unp1RkB5qsyGcG4QEouF_AtusbrmVmhtJkpGDPA6kkE",
     *                 "updateTime": "2016-09-01 18:41:04",
     *                 "content": {
     *                     "articles": [
     *                         {
     *                             "thumbMediaId": "unp1RkB5qsyGcG4QEouF_OfnZMo9oLlOOm1NKblPoaI",
     *                             "thumbUrl": "http://mmbiz.qpic.cn/mmbiz_jpg/HtVebh70FQaujkpzQ9pBPic74WfNh26veTOseARVjpDOBvURvafuKib9WLQV77FBboTnNSu2Uwk7mmc9SBkMCdRw/0?wx_fmt=jpeg",
     *                             "author": "乐宸科技",
     *                             "title": "搜索",
     *                             "contentSourceUrl": "",
     *                             "content": "<p>
     * 	试试事实上是是是是是是是是是是是是试试事实上是是是是是是是是是
     * </p >
     * <p>
     * 	< img  />",
     *                             "digest": "digest",
     *                             "showCoverPic": false,
     *                             "url": "http://mp.weixin.qq.com/s?__biz=MzAwMzEwODY5MQ==&mid=477451460&idx=1&sn=ccb71be47579543de00c27ba09883e65#rd"
     *                         }
     *                     ],
     *                     "empty": false
     *                 }
     *             }
     *         ]
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MATERIAL_NEWSBATCHGET, method = RequestMethod.GET)
    @ResponseBody
    private JsonResult newsBatchGet(HttpServletRequest request, int offset, int count) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            String domain = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(domain)) {
                domain = mall.getMobileHostName();
            }
            jsonResult.data=mallWechatMenuConfigSrvImpl.materialNewsBatchGet(domain,offset, count).data;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/wechat/material/info B端 获取微信永久素材
     * @apiGroup MALL_WECHAT_MATERIAL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} type <code>必传参数</code> 素材的类型图文（news） 图片（image）、视频（video）、语音 （voice）
     * @apiParam {String} mediaId <code>必传参数</code> 素材ID
     *
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} url URL
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": "1",
     *     "desc": "成功",
     *     "data": {
     *         "code": "1",
     *         "desc": "成功",
     *         "data": {
     *             "articles": [
     *                 {
     *                     "thumbMediaId": "unp1RkB5qsyGcG4QEouF_OfnZMo9oLlOOm1NKblPoaI",
     *                     "thumbUrl": "http://mmbiz.qpic.cn/mmbiz_jpg/HtVebh70FQaujkpzQ9pBPic74WfNh26veTOseARVjpDOBvURvafuKib9WLQV77FBboTnNSu2Uwk7mmc9SBkMCdRw/0?wx_fmt=jpeg",
     *                     "author": "乐宸科技",
     *                     "title": "搜索",
     *                     "contentSourceUrl": "",
     *                     "content": "<p>
     * 	试试事实上是是是是是是是是是是是是试试事实上是是是是是是是是是
     * </p >
     * <p>
     * 	< img  />",
     *                     "digest": "digest",
     *                     "showCoverPic": false,
     *                     "url": "http://mp.weixin.qq.com/s?__biz=MzAwMzEwODY5MQ==&mid=477451460&idx=1&sn=ccb71be47579543de00c27ba09883e65#rd"
     *                 }
     *             ],
     *             "empty": false
     *         }
     *     }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MATERIAL_INFO, method = RequestMethod.GET)
    @ResponseBody
    private JsonResult getMaterialInfo(HttpServletRequest request, String type, String mediaId) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            String domain = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(domain)) {
                domain = mall.getMobileHostName();
            }
            jsonResult.data=mallWechatMenuConfigSrvImpl.getMaterialInfo(domain,type,mediaId).data;
        };
        return doing.go(request, log);
    }
}
